package com.ruoyi.data.opc.config;

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig;
import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
import org.eclipse.milo.opcua.stack.client.UaTcpStackClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;

public class Client {
    public static Lock lock = new ReentrantLock();

    /**
     * 创建OPC UA的服务连接对象
     * @param url 需要连接的url
     * @return
     * @throws Exception
     */
    public static OpcUaClient createClient(String url) throws Exception {
        System.out.println("url------------" + url);
        Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
        Files.createDirectories(securityTempDir);
        if (!Files.exists(securityTempDir)) {
            throw new Exception("不能够创建安全路径: " + securityTempDir);
        }
        KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);
        // 获取OPC UA的服务器端节点
        EndpointDescription[] endpoints =
//                UaTcpStackClient.getEndpoints(opcUAClientService.getEndpointUrl()).get();
                UaTcpStackClient.getEndpoints(url).get();
//        System.out.println(opcUAClientService.getEndpointUrl().getClass());
        EndpointDescription endpoint = Arrays.stream(endpoints)
                .filter(e -> e.getEndpointUrl().equals(url))
                .findFirst().orElseThrow(() -> new Exception("没有节点返回"));

        // 设置OPC UA的配置信息
        OpcUaClientConfig config =
                OpcUaClientConfig.builder()
                        .setApplicationName(LocalizedText.english("OPC UA SCREEN"))
                        .setApplicationUri("urn:eclipse:milo:examples:client")
                        .setCertificate(loader.getClientCertificate())
                        .setKeyPair(loader.getClientKeyPair())
                        .setEndpoint(endpoint)
                        .setIdentityProvider(new AnonymousProvider())
//                        .setIdentityProvider(new UsernameProvider("Default User", "123456"))
                        .setRequestTimeout(uint(5000))
                        .build();
        // 创建OPC UA客户端
        return new OpcUaClient(config);
    }

    public static void onLock() {
        lock.lock();
    }

    public static void unLock() {
        lock.unlock();
    }
}
